package com.example.uploadimage.controller;

import com.example.uploadimage.constant.UploadImagePath;
import com.example.uploadimage.exceptionhandler.MyException;
import com.example.uploadimage.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/image")
@Api(tags = "上传到本地")
@CrossOrigin
//@Slf4j
public class UploadOnLocalController {

	static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

	//获取日志类 有@Slf4j注解下面这个不用写，可以直接log.info
	Logger logger = LoggerFactory.getLogger(UploadOnLocalController.class);


	@ApiOperation("上传文件到本地")
	@PostMapping("/upload/{location}") // location是作为保存在images目录下的哪个目录下的地址名称
	public Result uploadFile(@ApiParam(value="文件",required=true) @RequestPart("file") MultipartFile file,
						 @PathVariable("location") String location,
						 HttpServletRequest request) {
		System.out.println("----->" + new Date());
		if(file.isEmpty()) {
			throw new MyException(20001, "上传文件为空，请重新上传!!!");
		}

		// UUID + 文件后缀名 = 上传的文件名
		String fileName = String.format("%s.%s", UUID.randomUUID().toString(), file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1));

		String format = "/" + sdf.format(new Date()); // 20220311
//		String imageURL = "http://localhost:8009/images/" + location + format + "/"+ fileName;
		String imageURL = UploadImagePath.VisitBasicPath + location + format + "/"+ fileName;

		logger.info("上传源文件名 = " + file.getOriginalFilename() + "文件类型 = " + file.getContentType() + " 目标文件名：" + location + format +"/" + fileName);

		String localPath = UploadImagePath.IMG_UPLOAD_PATH + location + format;  // 存储的本地地址


//		System.out.println(imageURL);
		upload(file, localPath, fileName);
		logger.info("上传成功");
		return Result.ok().data("filePath", imageURL);
	}

	/**
	 *  保存文件到硬盘
	 * @param file
	 * @param filePath
	 * @param fileName
	 */
	public void upload(MultipartFile file, String filePath, String fileName) {
		// File info
		//保存到硬盘
		//路径示例 1) Windows c:/
		if(!new File(filePath).exists()){
			new File(filePath).mkdirs();
		}
		try {
			file.transferTo(new File(filePath + "/" + fileName));
		} catch (IOException e) {
			e.printStackTrace();
			throw new MyException(20001, "文件保存异常错误");
		}
	}

}